<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form id="loginForm">
        <div>
            <label>用户名：<input type="text" id="username" name="username"></label> <br>
            <label>密码：&nbsp;&nbsp;&nbsp;<input type="password" id="password" name="password"></label>
        </div>
        <button id="submit">登录</button>
    </form>
    <script>
        const loginForm = document.querySelector('#loginForm')
        loginForm.onsubmit = (e) => {
            e.preventDefault
            const xhr = new XMLHttpRequest()
            xhr.open('POST', 'http://ajax-api.itheima.net/api/login')
            xhr.setRequestHeader('content-type', 'application/json')
            const formData = new FormData(loginForm)
            xhr.send(JSON.stringify({
                username: formData.get('username'),
                password: formData.get('password')
            }))
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        alert('登录成功')
                    } else {
                        alert('登录失败')
                    }
                }
            }
        }
    </script>
</body>

</html>